<?php
// +----------------------------------------------------------------------
// | HisiPHP框架[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2021 http://www.HisiPHP.com
// +----------------------------------------------------------------------
// | HisiPHP承诺基础框架永久免费开源，您可用于学习和商用，但必须保留软件版权信息。
// +----------------------------------------------------------------------
// | Author: 橘子俊 <364666827@qq.com>，开发者QQ群：50304283
// +----------------------------------------------------------------------

namespace app\common\service;

use app\common\service\Base;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\CostCheck as CostCheckService;

class CheckclothShrink extends Base
{

	/**
	 * 根据ID获取详情
	 *
	 * @author KING
	 * @date 2020年7月29日
	 *
	 * @param integer $id
	 * @param string $field
	 * @return array
	 */
	public function getInfoById($id, $field='*') {
		if (empty($id)) return [];
		return db('checkcloth_shrink')->where('id', $id)->field($field)->findOrEmpty();
	}
        
        /**
	 * 根据ID获取详情
	 *
	 * @author KING
	 * @date 2020年7月29日
	 *
	 * @param integer $orderId
	 * @param string $field
	 * @return array
	 */
	public function getInfoByOrderId($orderId, $field='*') {
		if (empty($orderId)) return [];
		return db('checkcloth_shrink')->where('order_id', $orderId)->order('true_fabric_width asc')->field($field)->find();
	}

	/**
	 * 同步数据
	 *
	 * @author KING
	 * @date 2020年4月27日
	 *
	 * @param integer $orderId
	 * @param integer $materialId
         * @param integer $type
	 */
	public function syncData($orderId, $materialId,$type) {
		$omData = [];
		$unCheckclothInfo = db('order_material_item')->where("order_id = {$orderId} and material_id = {$materialId} and is_checkcloth = 0 and is_return = 0")->findOrEmpty();
		$unShrinkInfo = db('order_material_item')->where("order_id = {$orderId} and material_id = {$materialId} and is_shrink = 0 and is_return = 0")->findOrEmpty();
		// 验布缩水是否完成
        $this->is_over_checkcloth_shrink($orderId, $materialId);

		// 更新order_material数据
		$checkclothList = db('checkcloth_shrink')->where("order_id = {$orderId} and material_id = {$materialId} and type = 1 and is_return = 0")->select();
		$shrinkList = db('checkcloth_shrink')->where("order_id = {$orderId} and material_id = {$materialId} and type = 2 and is_return = 0")->select();
		$omData = [];
		$trueFabricWidth = 0;
		if (!$unCheckclothInfo && $checkclothList) { // 验布完成
			$trueFabricWidth = $omData['true_fabric_width'] = min(array_column($checkclothList, 'true_fabric_width'));
		}
		if (!$unShrinkInfo && $shrinkList) { // 缩水完成
			$omData['true_fabric_width'] = min(array_column($shrinkList, 'true_fabric_width'));

			// 最小幅宽需减掉布边损料
			$edgeDamage = 0;
			foreach ($shrinkList as $v) {
				if ($v['edge_damage'] > $edgeDamage && $v['true_fabric_width'] == $omData['true_fabric_width']) {
					$edgeDamage = $v['edge_damage'];
				}
			}
			$omData['true_fabric_width'] = $omData['true_fabric_width'] - $edgeDamage;

			$trueFabricWidth = min(array_column($shrinkList, 'fabric_width_shrink'));
		}
		$omData['checkcloth_length'] = array_sum(array_column($checkclothList, 'length'));
		$omData['shrink_length'] = array_sum(array_column($shrinkList, 'length'));
		$omData['weight_shrink'] = array_sum(array_column($shrinkList, 'weight_shrink'));
		$omData['weight_page'] = array_sum(array_column($shrinkList, 'weight_page'));

		$lengthShrink = array_sum(array_column($shrinkList, 'length_shrink'));
		if ($lengthShrink && $trueFabricWidth) {
			$omData['true_weight'] = round(($omData['weight_shrink'] - $omData['weight_page']) / ($lengthShrink / ($trueFabricWidth /100)) * 1000, 2);
		}
		if ($omData) {
			db('order_material')->where("order_id = {$orderId} and material_id = {$materialId}")->update($omData);
		}
        $createret=(new CostCheckService())->set_cost_check_select_10000_all([$orderId]);//判断并生成【幅宽】补损信息
        $createret=(new CostCheckService())->set_cost_check_select_3([$orderId]); //判断并生成【工艺染色】核价信息
		return true;
	}

    /**
     * 同步数据 --针对备料
     * @param integer $orderId
     * @param integer $materialId
     * @param integer $type
     */
    public function syncData_stock_m_type_1($mid,$type) {
        $omData = [];
        $unCheckclothInfo = db('order_material_item')->where("order_material_id = {$mid}  and is_checkcloth = 0 and is_return = 0")->findOrEmpty();
        $unShrinkInfo = db('order_material_item')->where("order_material_id = {$mid} and is_shrink = 0 and is_return = 0")->findOrEmpty();
        // 验布缩水是否完成
        $this->is_over_checkcloth_shrink_stock_m_type_1($mid);

        // 更新order_material数据
        $checkclothList = db('checkcloth_shrink')->where("stock_m_type = 1 and order_material_id = {$mid} and type = 1 and is_return = 0")->select();
        $shrinkList = db('checkcloth_shrink')->where("stock_m_type = 1 and order_material_id = {$mid} and type = 2 and is_return = 0")->select();
        $omData = [];
        $trueFabricWidth = 0;
        if (!$unCheckclothInfo && $checkclothList) { // 验布完成
            $trueFabricWidth = $omData['true_fabric_width'] = min(array_column($checkclothList, 'true_fabric_width'));
        }
        if (!$unShrinkInfo && $shrinkList) { // 缩水完成
            $omData['true_fabric_width'] = min(array_column($shrinkList, 'true_fabric_width'));

            // 最小幅宽需减掉布边损料
            $edgeDamage = 0;
            foreach ($shrinkList as $v) {
                if ($v['edge_damage'] > $edgeDamage && $v['true_fabric_width'] == $omData['true_fabric_width']) {
                    $edgeDamage = $v['edge_damage'];
                }
            }
            $omData['true_fabric_width'] = $omData['true_fabric_width'] - $edgeDamage;

            $trueFabricWidth = min(array_column($shrinkList, 'fabric_width_shrink'));
        }
        $omData['checkcloth_length'] = array_sum(array_column($checkclothList, 'length'));
        $omData['shrink_length'] = array_sum(array_column($shrinkList, 'length'));
        $omData['weight_shrink'] = array_sum(array_column($shrinkList, 'weight_shrink'));
        $omData['weight_page'] = array_sum(array_column($shrinkList, 'weight_page'));

        $lengthShrink = array_sum(array_column($shrinkList, 'length_shrink'));
        if ($lengthShrink && $trueFabricWidth) {
            $omData['true_weight'] = round(($omData['weight_shrink'] - $omData['weight_page']) / ($lengthShrink / ($trueFabricWidth /100)) * 1000, 2);
        }
        if ($omData) {
            db('order_material')->where("mid = {$mid}")->update($omData);
        }

        return true;
    }

    /**
     * 验布缩水是否完成
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/16
     */
    public function is_over_checkcloth_shrink($orderId, $materialId)
    {
        //1,查询条数，与现在的 验布缩水的条数。
        $order_material_info = db('order_material')->field('order_id,material_id,tiaoshu')->where("order_id = {$orderId} and material_id = {$materialId}")->find();
        $checkcloth_count = db('order_material_item')->where("order_id = {$orderId} and material_id = {$materialId} and is_checkcloth = 1 and is_return = 0")->count();
        $shrink_count = db('order_material_item')->where("order_id = {$orderId} and material_id = {$materialId} and is_shrink = 1 and is_return = 0")->count();
        if ($order_material_info['tiaoshu'] <= 0) {
            return false;
        }
        //2,
        if ($order_material_info['tiaoshu'] == $checkcloth_count) {
            $a = db('checkcloth_shrink')
                ->where("order_id = {$orderId} and material_id = {$materialId} and type = 1")
                ->update([
                    'over_time' => time(),
                    'update_time' => time(),
                ]);
        }
        if ($order_material_info['tiaoshu'] == $shrink_count) {
            $a = db('checkcloth_shrink')
                ->where("order_id = {$orderId} and material_id = {$materialId} and type = 2")
                ->update([
                    'over_time' => time(),
                    'update_time' => time(),
                ]);
        }
        return true;
    }

    /**
     * 验布缩水是否完成--针对备料
     * @author zhuguosen 905502314@qq.com
     * @date 2022/4/16
     */
    public function is_over_checkcloth_shrink_stock_m_type_1($mid)
    {
        //1,查询条数，与现在的 验布缩水的条数。
        $order_material_info = db('order_material')->field('order_id,material_id,tiaoshu')->where("mid = {$mid}")->find();
        $checkcloth_count = db('order_material_item')->where("order_material_id = {$mid}  and is_checkcloth = 1 and is_return = 0")->count();
        $shrink_count = db('order_material_item')->where("order_material_id = {$mid}  and is_shrink = 1 and is_return = 0")->count();
        if ($order_material_info['tiaoshu'] <= 0) {
            return false;
        }
        //2,
        if ($order_material_info['tiaoshu'] == $checkcloth_count) {
            $a = db('checkcloth_shrink')
                ->where("stock_m_type = 1 and order_material_id = {$mid} and type = 1")
                ->update([
                    'over_time' => time(),
                    'update_time' => time(),
                ]);
        }
        if ($order_material_info['tiaoshu'] == $shrink_count) {
            $a = db('checkcloth_shrink')
                ->where("stock_m_type = 1 and order_material_id = {$mid} and type = 2")
                ->update([
                    'over_time' => time(),
                    'update_time' => time(),
                ]);
        }
        return true;
    }


    /**
	 * 多料处理
	 *
	 * @author KING
	 * @date 2020年5月25日
	 *
	 * @param integer $orderId
	 * @param integer $materialId
	 */
	public function excess($orderId, $materialId) {
		$needDosage = (new OrderMaterialService())->getNeedDosage($orderId, $materialId);
		if ($needDosage > 0) {
			$list = db('checkcloth_shrink')->where("order_id = {$orderId} and material_id = {$materialId} and type = 2 and is_return = 0")->order("length desc")->select();
			$count = 0;
			$isOver = false;
			foreach ($list as $k => $v) {
				if ($isOver) {	// update is_excess=1
					db('checkcloth_shrink')->where('id', $v['id'])->update(['is_excess' => 1]);
				}

				$count += $v['length'];
				if ($count/$needDosage >= 0.8) {
					$isOver = true;
				}
			}
		}
	}

	/**
	 * 计算预计完成时间
	 *
	 * @author KING
	 * @date 2020年5月26日
	 *
	 * @param integer $type		1验布，2缩水
	 * @param number $todoNum	未完成数量
	 */
	public function calPlanOverTime($type, $todoNum=0) {
		if ($todoNum == 0) return '';
		$list = db('checkcloth_shrink')->where("type = {$type}")->order("create_time desc")->limit(100)->field('create_time')->select();
		$timeArr = [];
		$lastTime = 0;
		foreach ($list as $v) {
			if ($lastTime == 0) $lastTime = $v['create_time'];
			$diff = $lastTime - $v['create_time'];
			if ($diff >= 180 && $diff <= 420) {
				$timeArr[] = $diff;
			}
		}
		if ($timeArr) {
			$avgTime = round(array_sum($timeArr)/count($timeArr));
		} else $avgTime = $type == 1 ? (5*30) : (6.5*30);

		$needTime = $avgTime * $todoNum;
		$workTimeStart = 8;
		$workTimeEnd = 22;
		if(intval(date("H")) >= $workTimeEnd || intval(date("H")) < $workTimeStart) {
			$leftTime = $needTime;
		} else {
			$todaySeconds = strtotime(date("Y-m-d {$workTimeEnd}:00:00"))-time();
			if ($todaySeconds > $needTime) {
				return date("Y-m-d H:i", time()+$needTime);
			} else {
				$leftTime = $needTime - $todaySeconds;
			}
		}
		$oneDaySeconds = ($workTimeEnd-$workTimeStart)*3600;
		$days = ceil($leftTime/$oneDaySeconds);
		$times = $leftTime%$oneDaySeconds;
		return date("Y-m-d H:i", mktime($workTimeStart,0,$times,date('m'),date('n')+$days,date('Y')));
	}
}